package com.journaldev.spring.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.journaldev.spring.model.District;

@Transactional
public class DistrictDAOImpl implements DistrictDAO {
	
	private static final Logger logger = LoggerFactory.getLogger(DistrictDAOImpl.class);

	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sf){
		this.sessionFactory = sf;
	}

	@Override
	public void addDistrict(District p) {
		Session session = this.sessionFactory.getCurrentSession();
		session.persist(p);
		logger.info("District saved successfully, District Details="+p);

	}

	@Override
	public void updateDistrict(District p) {
		Session session = this.sessionFactory.getCurrentSession();
		session.update(p);
		logger.info("District updated successfully, District Details="+p);

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<District> listDistrict() {
		Session session = this.sessionFactory.getCurrentSession();
		List<District> districtList = session.createQuery("from District").list();
		for(District p : districtList){
			logger.info("District List::"+p);
		}
		return districtList;
	}

	@Override
	public District getDistrictById(int id) {
		Session session = this.sessionFactory.getCurrentSession();		
		District p = (District) session.get(District.class, new Integer(id));
		logger.info("District loaded successfully, District details="+p);
		return p;
	}

	@Override
	public void removeDistrict(int id) {
		Session session = this.sessionFactory.getCurrentSession();
		District p = (District) session.get(District.class, new Integer(id));
		if(null != p){
			session.delete(p);
		}
		logger.info("District deleted successfully, District details="+p);

	}

}
